package com.yeung.ssm.handler;


import com.yeung.ssm.bean.EmployeeStatus;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义枚举类型处理器
 * 方便ibatis包装数据
 * <p>
 * <p>
 * 使用自定义的类型处理器, 直接在ibatis配置文件中配置
 */
public class EnumEmpStatusTypeHandler extends BaseTypeHandler<EmployeeStatus> {

    /**
     * 定义当前数据如何保存到数据库中
     *
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, EmployeeStatus parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getCode() + "");
    }

    @Override
    public EmployeeStatus getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);//从数据库中拿到枚举对象的code
        EmployeeStatus employeeStatus = EmployeeStatus.newInstance(code);
        return employeeStatus;
    }

    @Override
    public EmployeeStatus getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        EmployeeStatus employeeStatus = EmployeeStatus.newInstance(code);
        return employeeStatus;
    }

    @Override
    public EmployeeStatus getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        EmployeeStatus employeeStatus = EmployeeStatus.newInstance(code);
        return employeeStatus;
    }
}
